<script lang="ts" setup>
import {onMounted, ref} from "vue";
import router from "@/router";
import axios from "axios";
import {useToast} from 'vue-toast-notification';
import 'vue-toast-notification/dist/theme-sugar.css';
const $toast = useToast();//消息提示栏
import crypto from '@/util/crypto'

const searchContent = ref('')
const searchOptions = [
  '香水',
  '配料',
  '品牌'
]
const searchOption = ref("香水")
//是否登录
const isLogin = ref(false)
//是否显示登录对话框
const isShowLogin = ref(false)
const email = ref('')
const password = ref('')
//购物车记录
const shopList = ref({
  buyList: [
    // {name: "香水香水香水香水1",
    // count: 999,
    // price: 99999.88,
    // id: 1,
    // img:""
    // }
  ],
  buyCount: 0
})
const ingredientList = ref([
  // {
  //   name: "石油花1",
  //   ingredientId: 9,
  //   img:""
  // }
])

//
const model = ref(0)

//检查是否登录
const checkLogin = () => {
  if (localStorage.getItem("wiki-auth-token")) {
    const token = localStorage.getItem("wiki-auth-token")
    axios.post("/api/auth/check", {}, {  // 这里传递空对象作为请求体
      headers: {
        token: token  // 使用token作为请求头
      }
    }).then(res => {
      // console.log(res);
      const msg = res.data.message;
      if (res.data.success) {
        // 成功的处理逻辑
        localStorage.setItem("wiki-auth-token", msg)
        isLogin.value = true;
        isShowLogin.value = false;
      }
    })
  } else {
    isLogin.value = false
  }

}
const ChoosePerfume = () => {
  router.push("/ingredient/choosePerfume")
  IngredientIsShow.value = false
}
//个人中心
const goMyPage = () => {
  router.push("/my")
}
//显示登录提示框
const showLogin = () => {
  isShowLogin.value = true
}
//关闭登录密码提示框
const quitLoginDia = () => {
  isShowLogin.value = false
}
const shopCartIsShow = ref(false)
const IngredientIsShow = ref(false)
const search = () => {
  console.log(searchOption.value)
  if(searchOption.value == "香水"){
    router.push("/perfume?name="+searchContent.value)
  }else if(searchOption.value == "配料"){
    router.push("/ingredient?name="+searchContent.value)
  }else{
    router.push("/bland?name="+searchContent.value)
  }
}
const showShopDialog = () => {
  if(!isLogin.value){
    $toast.open({
      message: "请先登录，再进行购物车操作",
      type: "error",
      position: "bottom-right"
    })
    return
  }
  initShopList()
  shopCartIsShow.value = true
}
const showIngredientDialog = () => {
  // if(!isLogin.value){
  //   $toast.open({
  //     message: "请先登录，再添加香料操作",
  //     type: "error",
  //     position: "bottom-right"
  //   })
  //   return
  // }
  initIngredientItem()
  IngredientIsShow.value = true
}
//移除某个配料
const removeIngredientItem = (index) => {
  ingredientList.value.splice(index, 1)
  saveIngredientInfo()
}
//移除某个香水
const removePerfumeItem = (index) => {
  shopList.value.buyList.splice(index, 1)
  saveShopList()
}
//创建香水档案
const createInfo = () => {

}

const saveIngredientInfo = () => {
  localStorage.setItem("Ingredient-data-list", JSON.stringify(ingredientList.value))
}

//保存购物信息系
const saveShopList = () => {
  localStorage.setItem("shopCart-data-list", JSON.stringify(shopList.value.buyList))
}

//检查购物车数量的操作并保存
const checkShopCount = (e) => {

  // let val = e.originalTarget._value
  console.log("购物车数据发生变化")
  let count = 0 //初始化金额为0

  //数量不可小于1
  for (let i = 0; i < shopList.value.buyList.length; i++) {
    if (shopList.value.buyList[i].count < 0) {
      shopList.value.buyList[i].count = 0
    }
  }
  //重新初始化计算
  shopList.value.buyList.forEach(el => {
    count += (el.count * el.price)
  })
  shopList.value.buyCount = count
  saveShopList()
}
//初始化购物车
const initShopList = () => {
  if (localStorage.getItem("shopCart-data-list")) {
    let shopList_ = JSON.parse(localStorage.getItem("shopCart-data-list"))
    shopList.value.buyList = shopList_
    let count = 0 //初始化金额为0
    shopList_.forEach(el => {
      count += (el.count * el.price)
    })
    shopList.value.buyCount = count
  } else {
    shopList.value.buyCount = 0
    shopList.value.buyList = []
  }
}

//登录
const login = () => {
  const data = {
    username: email.value,
    password: password.value
  }
  axios.post("/api/auth/login", data)
      .then(res => {
        console.log(res)
        const msg = res.data.message
        if (res.data.success) {
          localStorage.setItem("wiki-auth-token", msg)
          isLogin.value = true;
          isShowLogin.value = false;
          $toast.open({
            type: "success",
            message: "登录成功",
            position: "bottom-right"
          })
        } else {
          $toast.open({
            type: "error",
            message: "账号或者密码异常",
            position: "bottom-right"
          })
        }
      })
}
//重置密码
const goForgetPassword = () => {
  router.push("/forget")
  isShowLogin.value = false
}
//注册
const goRegister = () => {
  router.push("/register")
  isShowLogin.value = false
}

//初始化配料表
const initIngredientItem = () => {
  if (localStorage.getItem("Ingredient-data-list")) {
    let ingredientList_ = JSON.parse(localStorage.getItem("Ingredient-data-list"))
    ingredientList.value = ingredientList_
  } else {
    ingredientList.value = []
  }
}

const address = ref('')
onMounted(() => {
  checkLogin()
  initShopList()
  initIngredientItem()
})
const getMyOrderInfo = () => {
  if (localStorage.getItem("wiki-auth-token")) {
    axios.post("/api/auth/userinfo", {}, {
      headers: {
        token: localStorage.getItem("wiki-auth-token")
      }
    }).then(res => {
      console.log(res)
      if (res.data.success) {
        const msg = res.data.message
        console.log(msg)
        let enc = crypto.encrypt(msg.userPk)
        console.log(enc)
        // console.log(crypto.decrypt(enc))
        localStorage.setItem("wiki-user-flag", enc)
      } else {
        $toast.open({
          type: "error",
          message: "获取用户信息异常",
          position: "bottom-right"
        })
      }
    })
  }
}
getMyOrderInfo()

const createOrder = () => {
  if (!address.value) {
    return
  }
  let url = '/api/order/create';
  let data_ = JSON.parse(localStorage.getItem("shopCart-data-list"));

  // 构建 orderRecepts 数组
  let arr = []
  data_.forEach(el => {
    arr.push({
      id: el.id,
      count: el.count
    })
  });
  const data = {
    orderReceipts: arr,
    address: address.value
  }
  axios.post(url, data, {
    headers: {
      token: localStorage.getItem("wiki-auth-token")
    }
  })
      .then(res => {
        console.log(res);
        if (res.data.success) {
          shopCartIsShow.value = false
          $toast.open({
            type: "success",
            message: "购买成功",
            position: "bottom-right"
          })
          localStorage.removeItem("shopCart-data-list")
        } else {
          shopCartIsShow.value = false
          $toast.open({
            type: "error",
            message: "购买失败",
            position: "bottom-right"
          })
        }
      })
      .catch(error => {
        console.error(error);
        $toast.open({
          type: "error",
          message: "购买失败",
          position: "bottom-right"
        })
        shopCartIsShow.value = false
      });
};

</script>

<template>
  <div class="index-main">
    <div class="bgc"></div>
    <q-fab class="fab-item" color="teal" direction="left" icon="grid_view">
      <q-fab-action color="primary" icon="shopping_cart" @click="showShopDialog">
        <q-tooltip>
          购物车
        </q-tooltip>
      </q-fab-action>
      <q-fab-action color="pink-5" icon="local_florist" @click="showIngredientDialog">
        <q-tooltip>
          配料表
        </q-tooltip>
      </q-fab-action>
    </q-fab>
    <q-dialog v-model="shopCartIsShow" class="z-index-99999" persistent transition-hide="flip-up"
              transition-show="flip-down">
      <q-card style="min-width: 700px;">
        <q-markup-table bordered flat>
          <thead class="bg-teal text-white">
          <tr>
            <th colspan="5">
              <div class="row no-wrap items-center" style="display: flex;justify-content: space-between">
                <div class="text-h4 q-ml-md text-white flex items-center">
                  <q-icon name="local_grocery_store" size="40px"/>
                  购物车
                </div>
                <q-btn v-close-popup dense flat icon="close" round>
                  <q-tooltip>
                    关闭购物弹出
                  </q-tooltip>
                </q-btn>
              </div>
            </th>
          </tr>
          </thead>
          <q-virtual-scroll
              :items="shopList.buyList"
              :virtual-scroll-item-size="48"
              :virtual-scroll-sticky-size-end="32"
              :virtual-scroll-sticky-size-start="48"
              class="bg-grey-3"
              style="max-height: 50vh;min-height: 400px;"
              type="table"
          >
            <template v-slot:before>
              <thead class="thead-sticky text-left">
              <tr>
                <td class="text-center">
                  <q-icon name="numbers"/>
                </td>
                <td class="text-left">
                  <q-icon name="list"/>
                  香水
                </td>
                <td class="text-left">
                  <q-icon name="image"/>
                  图片
                </td>
                <td class="text-left">
                  <q-icon name="add_shopping_cart"/>
                  数量
                </td>
                <td class="text-center">
                  <q-icon name="attach_money"/>
                  金额
                </td>
                <td class="text-center">
                  <q-icon name="settings"/>
                  操作
                </td>
              </tr>
              </thead>
            </template>

            <template v-slot="{ item: row, index }">
              <tr :key="index">
                <td class="text-left">
                  {{ index + 1 }}
                </td>
                <td class="text-left"
                    style="max-width: 150px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;">
                  {{ row.name }}
                  <q-tooltip>{{ row.name }}</q-tooltip>
                </td>
                <td>
                  <img :src="row.img" alt="" style="height: 50px">
                </td>
                <td class="text-right">
                  <q-input
                      v-model.number="row.count"
                      filled
                      style="width: 100px"
                      type="number"
                      @update:model-value="checkShopCount"
                  >
                    <q-tooltip>
                      数量不可小于0
                    </q-tooltip>
                  </q-input>
                </td>
                <td class="text-right"
                    style="max-width: 130px;white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;"
                >
                  <q-icon name="attach_money"/>
                  <q-tooltip>{{ row.price }}</q-tooltip>
                  {{ row.price }}
                </td>
                <td>
                  <q-btn color="teal-2" icon="delete" square @click="removePerfumeItem(index)"/>
                </td>
              </tr>
            </template>
          </q-virtual-scroll>
        </q-markup-table>
        <q-form @submit="createOrder">
          <q-input v-model="address" :rules="[
          val =>  val !== '' || '请输入地址'
        ]" hint="请输入收货地址" label="address" style="width: 100%;"/>
          <div class="d-flex" style="justify-content: space-between">
            <q-btn :label="`Buy  All in  $ ${shopList.buyCount}`" color="teal-6" icon="paid"
                   style="width: 100%;height: 50px;" type="submit"/>
          </div>
        </q-form>
      </q-card>

    </q-dialog>
    <q-dialog v-model="IngredientIsShow" class="z-index-99999" persistent transition-hide="flip-up"
              transition-show="flip-down">
      <q-markup-table bordered flat>
        <thead class="bg-teal text-white">
        <tr>
          <th colspan="5">
            <div class="row no-wrap items-center" style="display: flex;justify-content: space-between">
              <div class="text-h4 q-ml-md text-white flex items-center">
                <q-icon name="local_grocery_store" size="40px"/>
                配料表
              </div>
              <q-btn v-close-popup dense flat icon="close" round>
                <q-tooltip>
                  关闭配料表弹出
                </q-tooltip>
              </q-btn>
            </div>
          </th>
        </tr>
        </thead>
        <q-virtual-scroll
            :items="ingredientList"
            :virtual-scroll-item-size="48"
            :virtual-scroll-sticky-size-end="32"
            :virtual-scroll-sticky-size-start="48"
            class="bg-grey-3"
            style="max-height: 40vh;min-height: 30vh;min-width: 300px"
            type="table"
        >
          <template v-slot:before>
            <thead class="thead-sticky text-left">
            <tr>
              <td class="text-center">
                <q-icon name="numbers"/>
              </td>
              <td class="text-left">
                <q-icon name="list"/>
                香料
              </td>
              <td class="text-left">
                <q-icon name="image"/>
                图片
              </td>
              <td class="text-center">
                <q-icon name="settings"/>
                操作
              </td>
            </tr>
            </thead>
          </template>

          <template v-slot="{ item: row, index }">
            <tr :key="index">
              <td class="text-left">
                {{ index + 1 }}
              </td>
              <td class="text-left"
                  style="width: 200px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;">
                {{ row.name }}
                <q-tooltip>{{ row.name }}</q-tooltip>
              </td>
              <td>
                <img :src="row.img" alt="" style="height: 50px">
              </td>
              <td>
                <q-btn color="red-4" icon="delete" square @click="removeIngredientItem(index)"/>
              </td>
            </tr>
          </template>
        </q-virtual-scroll>
        <div class="d-flex" style="justify-content: space-between">
          <q-btn :label="`确认配料`" color="teal" icon="check" style="width: 100%;height: 50px;"
                 @click="ChoosePerfume"/>
        </div>
      </q-markup-table>
    </q-dialog>
    <q-dialog v-model="isShowLogin" persistent style="z-index: 2" transition-hide="flip-up"
              transition-show="flip-down">
      <q-card style="width: 700px; max-width: 80vw;display: flex;height: 500px;">

        <q-img
            :ratio="16/9"
            src="/index/bg-login.png"
            style="flex:1"
        />

        <div
            style="flex: 1;margin-left: 40px;display: flex;align-items: start;flex-direction: column;justify-content: space-around">
          <div style="width: 90%">
            <div style="width: 100%;display: flex;justify-content: end">
              <q-btn color="grey-4" icon="close" outline round @click="quitLoginDia"/>
            </div>
            <div class="text-h6">登录</div>
            <div class="text-subtitle2">没有账户？
              <view class="link-to-other" style="margin-left: 30px;" @click="goRegister">注册</view>
            </div>
          </div>
          <q-form style="width: 90%" @submit="login">
            <div class="text-subtitle2">电子邮件</div>
            <q-input v-model="email" :rules="[
          val => val !== null && val !== '' || '请输入电子邮箱'
        ]" filled label="撰写电子邮箱" lazy-rules style="width: 100%"
                     type="email"
                     typeof="email"
            />
            <div class="text-subtitle2">密码</div>
            <q-input v-model="password" :rules="[
          val => val !== null && val !== '' || '请输入密码'
        ]" filled label="输入密码"
                     lazy-rules
                     style="width: 100%"
                     type="password"/>
            <div class="link-to-other" style="margin-top: 40px;" @click="goForgetPassword">我忘记了密码</div>
            <q-btn color="black" label="访问" stack stretch
                   style="width: 90%;padding-top: 5px;padding-bottom: 5px;margin-top: 40px;"
                   type="submit"/>
          </q-form>

        </div>
      </q-card>
    </q-dialog>

    <div class="header">
      <div class="flex" style="align-items: center;margin-left: 2vw;">
        <div class="logo" @click="router.push('/')">WIKIPARFUM</div>
        <ul class="flex" style="list-style: none">
          <li @click="router.push('/perfume')">香水</li>
          <li @click="router.push('/ingredient')">配料</li>
          <li @click="router.push('/bland')">品牌</li>
        </ul>
      </div>
      <div class="flex" style="margin-right: 2vw;">
        <q-select v-model="searchOption" :options="searchOptions" label="Standard"/>
        <q-input v-model="searchContent" color="teal" debounce="1000" filled
                 label="搜索"
                 outlined
                 placeholder="Search"
                 @keyup.enter="search"
        >
          <template v-slot:append>
            <q-icon class="cursor-pointer" name="search" @click="search"/>
          </template>
        </q-input>
        <view class="d-flex align-item-center cursor-pointer" style="margin-left: 10px;"
              @click="isLogin ? goMyPage() : showLogin()">
          <q-icon name="account_circle" size="20px" style="margin-right: 10px;"/>
          {{ isLogin ? "个人中心" : "登录" }}
        </view>
      </div>

    </div>
    <div class="header-back"></div>
    <router-view/>
  </div>
</template>

<style lang="scss" scoped>
.bgc {
  height: 100vh;
  width: 100vw;
  background-color: #f8f6f3;
  z-index: -1;
  top: 0;
  position: fixed;
}

.link-to-other {
  color: #8e7749;
  text-decoration: underline;
  cursor: pointer;
  text-decoration-color: #8e7749; /* 设置下划线为蓝色 */
}

.index-main {
  width: 100vw;
  .parallax {
    width: 100vw;
  }

  .logo {
    font-size: 25px;
    font-weight: 100;
    color: #b9ae99;
    cursor: pointer;
  }

  .header {
    z-index: 199999;
    position: fixed;
    height: 80px;
    display: flex;
    align-items: center;
    width: 100vw;
    background-color: #fff;
    justify-content: space-between;
  }

  .header-back {
    height: 80px;
  }

  ul > li {
    margin: 20px;
    cursor: pointer;
  }

  .fab-item {
    position: fixed;
    right: 10vw;
    bottom: 20vh;
  }
}

.thead-sticky tr > *,
.tfoot-sticky tr > * {
  position: sticky;
  opacity: 1;
  z-index: 1;
  background: #009688;
  color: white;
}

.thead-sticky tr:last-child > * {
  top: 0;
}

.tfoot-sticky tr:first-child > * {
  bottom: 0;
}


</style>